package com.windy.tag;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;

public class Pagination extends Component {
	public Pagination(ValueStack stack) {
		super(stack);
	}

	private String curPage;
	private String pageSize;
	private String totalRecords;
	private String actionPath;
	private HashMap<Object, Object> paramMap;

	public String getCurPage() {
		return curPage;
	}

	public void setCurPage(String curPage) {
		this.curPage = curPage;
	}

	public String getPageSize() {
		return pageSize;
	}

	public void setPageSize(String pageSize) {
		this.pageSize = pageSize;
	}

	public String getTotalRecords() {
		return totalRecords;
	}

	public void setTotalRecords(String totalRecords) {
		this.totalRecords = totalRecords;
	}

	public String getActionPath() {
		return actionPath;
	}

	public void setActionPath(String actionPath) {
		this.actionPath = actionPath;
	}

	public HashMap<Object, Object> getParamMap() {
		return paramMap;
	}

	public void setParamMap(HashMap<Object, Object> paramMap) {
		this.paramMap = paramMap;
	}

	/** ***************************************************************************** */
	public boolean start(Writer writer) {
		boolean result = super.start(writer);

		curPage = (String) getStack().findValue(trim(curPage), String.class);
		pageSize = (String) getStack().findValue(trim(pageSize), String.class);
		totalRecords = (String) getStack().findValue(trim(totalRecords),
				String.class);
		writeContent(writer);

		return result;
	}

	private String trim(String value) {
		if (value.startsWith("%{") && value.endsWith("}")) {
			value = value.substring(2, value.length() - 1);
		}
		return value;
	}

	private void writeContent(Writer writer) {
		try {
			writer.write("<form id='pForm' action='" + this.actionPath
					+ "' method='post'>");
			Iterator<Object> paramKeyIt = this.paramMap.keySet().iterator();
			//
			while (paramKeyIt.hasNext()) {
				Object key = paramKeyIt.next();
				Object value = this.paramMap.get(key);
				writer.write("<input type='hidden' name='" + key + "' value='"+ value + "'>");
			}
			writer.write("<input type='hidden' id='pFormAction' value=''>");
			//First
			writer.write("<input type=\"submit\" value=\"首页\" onclick=\"document.getElementById('pFormAction').value='doFirst'\"");
			writer.write("<input type=\"submit\" value=\"上一页\" onclick=\"document.getElementById('pFormAction').value='doPrev'\"");
			writer.write("<input type=\"submit\" value=\"下一页\" onclick=\"document.getElementById('pFormAction').value='doNext'\"");
			writer.write("<input type=\"submit\" value=\"尾页\" onclick=\"document.getElementById('pFormAction').value='doLast'\"");
			writer.write("</form>");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
